package com.example.andylau96.res.Main;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.andylau96.res.DataBase.UserDataBase;
import com.example.andylau96.res.Function.Cashier.xiaofeiFragment;
import com.example.andylau96.res.R;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener {

    public static Fragment now;
    public static DrawerLayout drawer;
    private static SimpleAdapter adapter;
    public static NavigationView na_view;
    public  static mainFragment main_frag;
    public static LinearLayout nav_hander_layou;
    public static int permission;
    public static int workid;
    private TextView hello;
    private SQLiteDatabase db;
    private Handler handler;
    private int hour;
    private int minute;
    private int second;
    private boolean isRunning=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permission=getIntent().getIntExtra("Permission",0);
        workid=getIntent().getIntExtra("WorkId",0);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        Init();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.framelayut, main_frag);
        now=main_frag;
        ft.commit();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        mainFragment.time.setText(hour+":"+minute+":"+second);
                }
            }
        };
        isRunning=true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(isRunning)
                {
                    try {
                        Thread.currentThread().sleep(1000);
                        second++;
                        if(second==60)
                        {
                            second=0;
                            minute++;
                        }
                        if(minute==60)
                        {
                            minute=0;
                            hour++;
                        }
                        Message mg=new Message();
                        mg.what=0;
                        handler.sendMessage(mg);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public void Init() {
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        na_view = (NavigationView) findViewById(R.id.nav_view);
        na_view.setNavigationItemSelectedListener(this);
        nav_hander_layou= (LinearLayout) na_view.getHeaderView(0);
        hello= (TextView) nav_hander_layou.findViewById(R.id.textView);
        adapter = new SimpleAdapter(this, getData(), R.layout.theme_item,
                new String[]{"color", "ok"},
                new int[]{R.id.item_imview, R.id.item_txview});
        main_frag = new mainFragment();
        db=new UserDataBase(this).getReadableDatabase();
        Cursor cr=db.rawQuery("select *from worker where WorkId="+workid,null);
        cr.moveToFirst();
        String name=cr.getString(cr.getColumnIndex("Name"));
        hello.setText("当前用户："+name);
        String time=cr.getString(cr.getColumnIndex("Time"));
        String temp[]=time.split("-");
        hour=Integer.valueOf(temp[0]);
        minute=Integer.valueOf(temp[1]);
        second=Integer.valueOf(temp[2]);
        cr.close();
        try {
            FileInputStream in;
            in = openFileInput("color.txt");
            in.close();
        } catch (Exception e) {
            try {
                String theme = "#12b7f5";
                FileOutputStream crate = openFileOutput("color.txt", MODE_PRIVATE);
                crate.write(theme.getBytes());
                crate.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        try {
            FileInputStream in;
            in = openFileInput("orderid.txt");
            in.close();
        } catch (Exception e) {
            try {
                String id = "1";
                FileOutputStream crate = openFileOutput("orderid.txt", MODE_PRIVATE);
                crate.write(id.getBytes());
                crate.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        try {
            FileInputStream in;
            in = openFileInput("dinningid.txt");
            in.close();
        } catch (Exception e) {
            try {
                String id = "1";
                FileOutputStream crate = openFileOutput("dinning.txt", MODE_PRIVATE);
                crate.write(id.getBytes());
                crate.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.main_title_left)
            drawer.openDrawer(Gravity.RIGHT);
    }

    private List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("color", R.color.color1);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color2);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color3);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color4);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color5);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color6);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color7);
        map.put("ok", R.drawable.ok_write);
        list.add(map);

        map = new HashMap<String, Object>();
        map.put("color", R.color.color8);
        map.put("ok", R.drawable.ok_write);
        list.add(map);
        return list;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_color) {
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.framelayut,new changeFragment());
            ft.addToBackStack(null);
            ft.commit();
        }
        if(id==R.id.nav_company)
        {
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.framelayut,new myCompany());
            ft.addToBackStack(null);
            ft.commit();
        }
        if(id==R.id.nav_changepwd)
        {
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.framelayut,new pwdFragment());
            ft.addToBackStack(null);
            ft.commit();
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public static SimpleAdapter getAdapter() {
        return adapter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.execSQL("update worker set Time='"+hour+"-"+minute+"-"+second+"' where WorkId="+workid);
        db.close();
        isRunning=false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==event.KEYCODE_BACK&&now instanceof xiaofeiFragment)
        {
            if(((xiaofeiFragment) now).onKeyDown(keyCode,event))
            {
                return true;
            }
            else
            {
                getFragmentManager().popBackStack();
                return  true;
            }
        }
        else
        {
            return super.onKeyDown(keyCode,event);
        }
    }
}

